﻿#region Using Declarations

using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Data.Entity.ModelConfiguration.Conventions;
using SocialFront.Core.Domain;

#endregion

namespace SocialFront.Core.Persistence
{
    public class SocialFrontContext : DbContext
    {
        // Db Sets...  
        public DbSet<Foo> Foos { get; set; }

        public DbSet<Product> Products { get; set; }
        public DbSet<ProductSize> ProductSizes { get; set; }
        public DbSet<ProductColor> ProductColors { get; set; }
        public DbSet<Category> Categories { get; set; }
        
        public DbSet<Courier> Couriers { get; set; }
        public DbSet<ShippingService> ShippingServices { get; set; }
        
        public DbSet<Customer> Customers { get; set; }
        public DbSet<DeliveryAddress> DeliveryAddresses { get; set; }
        public DbSet<Email> Emails { get; set; }
        
        public DbSet<Merchant> Merchants { get; set; }
        public DbSet<Order> Orders { get; set; }
        public DbSet<OrderItem> OrderItems { get; set; }

        public SocialFrontContext()
        {
            Configuration.LazyLoadingEnabled   = false;
            Configuration.ProxyCreationEnabled = true;
        }
      
        public override int SaveChanges()
        {
            try
            {
                return base.SaveChanges();
            }
            catch (DbEntityValidationException dbEntityValidationException)
            {
                var errors = new StringBuilder();

                foreach (var validationError in dbEntityValidationException
                                                     .EntityValidationErrors
                                                     .SelectMany(validationErrors => validationErrors.ValidationErrors))
                {
                    errors.AppendFormat("Property: {0} Error: {1}\n", validationError.PropertyName, validationError.ErrorMessage);
                }

                Debug.Print(errors.ToString());

                throw;
            }
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            // Add fluent stuff here. 
            modelBuilder.ComplexType<Address>();

            // The one to many cascade delete convention is a pain in the butt.
            modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
        }
    }
}
